package com.ld.task;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

/**
 * 遍历目录(含有子目录)找到指定文件。(分而治之ForkJoin异步用法:不要求有返回值,继承RecursiveAction)
 */
public class UseForkJoin extends RecursiveAction {
    private File filePath;

    public UseForkJoin(File filePath) {
        this.filePath = filePath;
    }

    @Override
    protected void compute() {
        List<UseForkJoin> subTasks = new ArrayList<>();
        File[] files = filePath.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    subTasks.add(new UseForkJoin(file));
                } else {
                    if (file.getAbsolutePath().endsWith("txt")) {
                        System.out.println("文件：" + file.getAbsolutePath());
                    }
                }
            }
            if (!subTasks.isEmpty()) {
                for (UseForkJoin useForkJoin : invokeAll(subTasks)) {
                    useForkJoin.join();
                }
            }
        }
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool(6);
        UseForkJoin useForkJoin = new UseForkJoin(new File("d:/"));
        forkJoinPool.execute(useForkJoin);//异步调用
//        forkJoinPool.invoke(useForkJoin);//同步调用
        long start = System.currentTimeMillis();
        System.out.println("Task is running...");
        try {
            Thread.sleep(1000);
            System.out.println("执行主线程方法。。。。");
            Thread.sleep(5000);
            useForkJoin.join();
            long end = System.currentTimeMillis();
            System.out.println("Task is end.时间=" + (end - start));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
